<!-- 受试者 -->
<template>
  <div>
    <s-table ref="table" rowKey="id" :columns="$auth('PROJECT.PROJECT_PATIENT_LIST') ? columns:[]" bordered :data="loadData">
      <template slot="title">
        <a-descriptions title="受试者管理"></a-descriptions>
        <div class="table-page-search-wrappers">
          <!-- 筛选区域 -->
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-item label="所属中心">
                  <a-select v-model="queryParam.researchId" allowClear>
                    <!-- <a-select-option v-for="item in centerList" :value="item.id" :key="item.id"> -->
                    <a-select-option v-for="item in centerList" :value="item.id" :key="item.id">
                      {{ item.orgName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="受试者状态">
                  <a-select v-model="queryParam.ptsStatus" allowClear>
                    <a-select-option v-for="(item, index) in $const.PTS_STATUS" :value="item.value" :key="index">
                      {{ item.desc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!-- <a-col :md="6" :sm="24">
                <a-form-item label="当前状态">
                  <a-input v-model="queryParam.id" placeholder="请选择当前状态" />
                </a-form-item>
              </a-col> -->
              <a-col :md="4" :sm="24">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" @click="activeQuery">查询</a-button>
                  <a-button style="margin-left: 8px" @click="resetParams">重置</a-button>
                  <a-button style="margin-left: 8px" icon="export" @click="clickExport" v-if="$auth('PROJECT.PROJECT_PATIENT_EXPORT')">导出</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
          <a-button type="primary" icon="plus" v-if="$auth('PROJECT.PROJECT_PATIENT_INVITE')" @click="addInvitation()">邀请</a-button>
        </div>
      </template>
      <template slot="orgName" slot-scope="text, record">
        <span>{{ record.researchCenterNo + '-' + record.orgName }} </span>
      </template>
      <template slot="ptsStatus" slot-scope="text, record">
        <span>{{ record.ptsStatus | filtersState }} </span>
      </template>
      <template slot="authStatus" slot-scope="text, record">
        <span>{{ record.authStatus | filterAuth }} </span>
      </template>
      <template slot="ptsGender" slot-scope="text, record">
        <span>{{ record.ptsGender | filterGender }} </span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <template>
          <a style="margin-right: 10px" v-if="record.authStatus != 4 && $auth('PROJECT.PROJECT_PATIENT_DETAIL') && !$auth('PROJECT.PROJECT_PATIENT_EDIT')" @click="acticeView(record, 0)">查看</a>
          <a style="margin-right: 10px" v-if="record.authStatus != 4 && $auth('PROJECT.PROJECT_PATIENT_EDIT')" @click="acticeView(record, 1)">编辑</a>
          <a-popconfirm :title="record.authStatus === 5 ? '确定邀请？' : '确定重新邀请？'" @confirm="clickReinvite(record)">
            <a style="margin-right: 10px" v-if="(record.authStatus == 5 || record.authStatus == 4 || record.authStatus == 2) && $auth('PROJECT.PROJECT_PATIENT_EDIT')">
              {{ record.authStatus === 5 ? '邀请' : '重新邀请' }}
            </a>
          </a-popconfirm>
          <a-popconfirm okText="确定" cancelText="取消" title="确定取消？" @confirm="actionDetail(record)">
            <a style="margin-right: 10px" v-if="record.authStatus == 4 && $auth('PROJECT.PROJECT_PATIENT_EDIT')">取消</a>
          </a-popconfirm>
        </template>
      </template>
    </s-table>
    <!-- 添加受试者 -->
    <AddSubject
      ref="addSubject"
      :visible="visible"
      @ok="handleOk"
      @cancel="closeAdd()"
      :centerList="centerList"
      :datailId="datailId"
      @import="handleImport"
    />
    <!-- 查看弹窗 -->
    <ViewModal
      :visible="viewVisible"
      @close="viewVisible = false"
      @closeViewModal="closeViewModal"
      :uId="uId"
      :isEdit="isEdit"
      :thisStatus="thisStatus"
      ref="viewModalRef"
    />
    <ResolveModal :visible="viewVisibleRes" @close="viewVisible = false" />
  </div>
</template>

<script>
import store from '@/store'
import monitor from '@/utils/monitor'
import subject from '@/monitor/views/overview/detail/responsible/components/subject/subject.js'

// import { list, centerList, addPts, delPts, getSubjectExport, reinviteSubject } from '@/api/overview/subject'
import { list, addPts, delPts, getSubjectExport, reinviteSubject } from '@/api/overview/subject'
import { getContractCenter } from '@/api/overview/member.js'
import AddSubject from './addSubjectModal.vue'
import ViewModal from './subject/viewModal.vue' // 查看页面
import ResolveModal from './subject/resolveModal.vue' // 审核弹框
import { exportExcel } from '@/utils/util'
import { buildPaginationObj } from '@/components/Table'
const watch = monitor(subject)
const columnsOther = [
  {
    title: '研究中心',
    dataIndex: 'orgName',
    scopedSlots: { customRender: 'orgName' }
  },
  {
    title: '受试者编号',
    dataIndex: 'ptsNo'
  },
  {
    title: '受试者状态',
    dataIndex: 'ptsStatus',
    scopedSlots: { customRender: 'ptsStatus' }
  },
  {
    title: '研究员',
    dataIndex: 'userName'
  }
]
const columnsCrcVisible = [
  {
    title: '研究中心',
    dataIndex: 'orgName',
    scopedSlots: { customRender: 'orgName' }
  },
  {
    title: '受试者编号',
    dataIndex: 'ptsNo'
  },
  {
    title: '受试者状态',
    dataIndex: 'ptsStatus',
    scopedSlots: { customRender: 'ptsStatus' }
  },
  {
    title: '电话/手机 ',
    dataIndex: 'ptsPhone',
    scopedSlots: { customRender: 'ptsPhone' }
  },
  {
    title: '患者姓名',
    dataIndex: 'ptsName',
    scopedSlots: { customRender: 'ptsName' }
  },
  {
    // 性别 1男 0女 -1未知
    title: '性别',
    dataIndex: 'ptsGender',
    scopedSlots: { customRender: 'ptsGender' }
  },
  {
    // 审批状态 1：接受 2：拒绝 3：待处理 4：待加入 5: 待邀请
    title: '审批状态',
    dataIndex: 'authStatus',
    scopedSlots: { customRender: 'authStatus' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

const columnsCrcInVisible = [
  {
    title: '研究中心',
    dataIndex: 'orgName',
    scopedSlots: { customRender: 'orgName' }
  },
  {
    title: '受试者编号',
    dataIndex: 'ptsNo'
  },
  {
    title: '受试者状态',
    dataIndex: 'ptsStatus',
    scopedSlots: { customRender: 'ptsStatus' }
  },

  {
    // 性别 1男 0女 -1未知
    title: '性别',
    dataIndex: 'ptsGender',
    scopedSlots: { customRender: 'ptsGender' }
  },
  {
    // 审批状态 1：接受 2：拒绝 3：待处理 4：待加入 5: 待邀请
    title: '审批状态',
    dataIndex: 'authStatus',
    scopedSlots: { customRender: 'authStatus' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]
export default {
  props: {
    datailId: {
      type: [String, Number],
      default: null
    }
  },
  name: 'Subject',
  components: {
    AddSubject,
    ViewModal,
    ResolveModal
  },
  data () {
    return {
      columns: [], // CRC和其他的角色看到的columns不一样
      visible: false,
      viewVisible: false,
      viewVisibleRes: false,
      centerList: [],
      filterCenterList: [],
      uId: '',
      thisStatus: '',
      queryParam: {
        proId: this.$route.query.id
      },
      loadData: parameter => {
        if (this.$auth('PROJECT.PROJECT_PATIENT_LIST')) {
          return list(Object.assign(parameter, this.queryParam)).then(res => {
            console.log(res)

            this.filterCenterList = this.filterList(res.content)
            return res
          })
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      isEdit: 0 // 0查看/1编辑受试者
    }
  },
  created () {
    // 如果有操作权限
    if (this.$auth('PROJECT.PROJECT_PATIENT_DETAIL') || this.$auth('PROJECT.PROJECT_PATIENT_EDIT')) {
      this.columns = this.$options.filters.isPtsVisible() ? columnsCrcVisible : columnsCrcInVisible
    } else {
      this.columns = columnsOther
    }

    this.getCenterList()
    console.log('store', store.getters.userInfo)
  },
  filters: {
    filtersState (val) {
      if (val === 1) {
        return '待筛选'
      } else if (val === 2) {
        return '筛选中'
      } else if (val === 3) {
        return '筛选失败'
      } else if (val === 4) {
        return '随机'
      } else if (val === 5) {
        return '治疗中'
      } else if (val === 6) {
        return '退出'
      } else if (val === 7) {
        return '治疗结束'
      } else if (val === 8) {
        return '安全性随访'
      } else if (val === 9) {
        return '生存随访'
      }
    },
    filterAuth (val) {
      if (val === 1) {
        return '接受'
      } else if (val === 2) {
        return '拒绝'
      } else if (val === 3) {
        return '待处理'
      } else if (val === 4) {
        return '待加入'
      } else if (val === 5) {
        return '待邀请'
      }
    },
    filterGender (val) {
      if (val === -1) {
        return '未知'
      } else if (val === 0) {
        return '女'
      } else if (val === 1) {
        return '男'
      }
    }
  },
  methods: watch({
    // 中心下拉列表
    getCenterList () {
      // centerList({ proId: this.$route.query.id, deleted: 0 }).then(res => {
      getContractCenter({ proId: this.$route.query.id, deleted: 0 }).then(res => {
      // centerList({ proId: this.$route.query.id, pageSize: 999999 }).then(res => {
        this.centerList = res.content
      })
    },
    filterList (arr) {
      const res = new Map()
      return arr.filter(arr => !res.has(arr.orgName) && res.set(arr.orgName, 1))
      // set语法设置的key为arr.orgName, value可随意，即可写1也可写其他
    },
    // 查询事件
    activeQuery () {
      // this.loadData(this.queryParam)
      this.$refs.table.refresh(true)
    },
    // 邀请
    addInvitation () {
      this.visible = true
    },
    // 清空params
    resetParams () {
      this.queryParam = {
        proId: this.$route.query.id
      }
      this.$refs.table.refresh(true)
    },
    handleOk (val, type) {
      // const arr = JSON.parse(JSON.stringify(this.$refs.addSubject.data))
      const arr = JSON.parse(JSON.stringify(val))
      arr.forEach(item => {
        delete item.key
        delete item.editable
        delete item.isNew
        delete item.siteOrgName
      })
      console.log('list', this.$refs.addSubject.data)
      addPts({
        type: type,
        proId: this.$route.query.id,
        proManagePtsList: JSON.stringify(arr)
      }).then(res => {
        this.$message.success('操作成功！')
        this.$refs.addSubject.data = [] // 清空数组
        this.visible = false
        this.$refs.table.refresh(true)
      })
    },
    // 打开查看弹窗
    acticeView (item, val) {
      this.viewSubject()
      this.uId = item.id
      this.thisStatus = item.authStatus
      this.viewVisible = true
      // alert(item.id)
      this.isEdit = val
      // this.$refs.viewModalRef.getPtsDetails(item.id)
    },
    // 重新邀请
    clickReinvite (record) {
      console.log(record, '当前行')
      reinviteSubject({ id: record.id, ptsNo: record.ptsNo, proId: this.$route.query.id, status: record.authStatus })
        .then(res => {
          this.$message.success(record.authStatus === 5 ? '邀请成功' : '重新邀请成功')
          this.$refs.table.refresh(true)
        })
        .catch(() => {
          this.$message.error(record.authStatus === 5 ? '邀请失败' : '重新邀请失败')
        })
    },
    actionDetail (value) {
      delPts({ id: value.id })
        .then(res => {
          console.log(res)
          this.$message.success('操作成功')
          this.$refs.table.refresh(true)
        })
        .catch(() => {
          this.$message.error('操作失败')
          this.$refs.table.refresh(true)
        })
    },
    // 关闭弹窗
    closeViewModal () {
      this.viewVisible = false
      this.$refs.table.refresh(true)
    },
    clickExport () {
      getSubjectExport({ proId: this.$route.query.id, researchId: this.queryParam.researchId, ptsStatus: this.queryParam.ptsStatus })
        .then(res => {
          exportExcel('受试者', res)
        })
        .catch(() => {})
    },
    // 关闭新增弹窗
    closeAdd () {
      this.visible = false
      this.$refs.addSubject.data = [] // 清空数组
    },
    // 查看受试者详情埋点
    viewSubject () {},
    // 导入成功回调
    handleImport () {
      this.visible = false
      this.$refs.table.refresh(true)
    }
  })
}
</script>
<style scoped lang="scss"></style>
